package edu.gzhu.guli.back.service.banner;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

import edu.gzhu.guli.core.common.ApplicationResult;
import edu.gzhu.guli.core.entity.Banner;
import edu.gzhu.guli.core.repository.BannerRepository;
import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class BannerService {

  final ModelMapper modelMapper;
  final BannerRepository bannerRepository;

  // 获取所有轮播图
  public ApplicationResult<List<BannerReadDto>> loadAll() {
    List<BannerReadDto> data = bannerRepository.findAll()
        .stream().map(it -> modelMapper.map(it, BannerReadDto.class))
        .collect(Collectors.toList());
    return ApplicationResult.succese(data);
  }

  // 新建轮播图
  public ApplicationResult<BannerReadDto> create(BannerCreateOrEditDto dto) {
    Banner banner = modelMapper.map(dto, Banner.class);
    banner = bannerRepository.save(banner);
    BannerReadDto data = modelMapper.map(banner, BannerReadDto.class);
    return ApplicationResult.succese(data);
  }

  // 编辑轮播图
  public ApplicationResult<BannerReadDto> edit(Long bannerId, BannerCreateOrEditDto dto) {
    Optional<Banner> check = bannerRepository.findById(bannerId);
    if (!check.isPresent())
      return ApplicationResult.failure("未找到目标轮播图");
    Banner banner = check.get();
    modelMapper.map(dto, banner);
    banner = bannerRepository.save(banner);
    BannerReadDto data = modelMapper.map(banner, BannerReadDto.class);
    return ApplicationResult.succese(data);
  }

  // 删除轮播图
  public ApplicationResult<Object> delete(Long bannerId) {
    bannerRepository.deleteById(bannerId);
    return ApplicationResult.succese();
  }
}
